<template>
  <XenPageLayout
    :title="pageTitle"
    title-align="left"
    :navbar-bg-color="themeConfig.primaryColor"
    navbar-text-color="#ffffff"
    navbar-icon-color="#ffffff"
    :contentStyle="gradientStyle"
  >
    <!-- 表单内容区域 -->
    <view class="form-container">
      <view class="form-card">
        <view class="form-header">
          <text class="form-title">{{ headerTitle }}</text>
          <text class="form-subtitle">{{ headerSubtitle }}</text>
        </view>

        <view class="form-content">
          <template v-for="section in formSections" :key="section.title">
            <!-- 表单分组 -->
            <view class="form-section">
              <view class="section-title">{{ section.title }}</view>

              <template v-for="field in section.fields" :key="field.key">
                <view class="form-item">
                  <text class="form-label">
                    <text v-if="field.required" class="required">*</text
                    >{{ field.label }}
                  </text>

                  <!-- 使用 v-show 替代 v-if 以提高微信小程序兼容性 -->
                  <!-- 文本输入 -->
                  <input
                    v-show="field.type === 'text'"
                    class="form-input"
                    type="text"
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                    :maxlength="field.maxlength"
                  />

                  <!-- 数字输入 -->
                  <input
                    v-show="field.type === 'number'"
                    class="form-input"
                    type="number"
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                  />

                  <!-- 选择器 -->
                  <picker
                    v-show="field.type === 'selector'"
                    class="form-picker"
                    mode="selector"
                    :range="field.options || []"
                    @change="
                      (e: any) =>
                        handleSelectorChange(field.key, e, field.options || [])
                    "
                  >
                    <view class="picker-content">
                      <text class="picker-text">{{
                        formData[field.key] || field.placeholder
                      }}</text>
                      <uni-icons type="down" size="14" color="#999"></uni-icons>
                    </view>
                  </picker>

                  <!-- 日期选择器 -->
                  <picker
                    v-show="field.type === 'date'"
                    class="form-picker"
                    mode="date"
                    :value="formData[field.key]"
                    @change="
                      (e: any) => handleFieldChange(field.key, e.detail.value)
                    "
                  >
                    <view class="picker-content">
                      <text class="picker-text">{{
                        formData[field.key] || field.placeholder
                      }}</text>
                      <uni-icons type="down" size="14" color="#999"></uni-icons>
                    </view>
                  </picker>

                  <!-- 时间选择器 -->
                  <picker
                    v-show="field.type === 'time'"
                    class="form-picker"
                    mode="time"
                    :value="formData[field.key]"
                    @change="
                      (e: any) => handleFieldChange(field.key, e.detail.value)
                    "
                  >
                    <view class="picker-content">
                      <text class="picker-text">{{
                        formData[field.key] || field.placeholder
                      }}</text>
                      <uni-icons type="down" size="14" color="#999"></uni-icons>
                    </view>
                  </picker>

                  <!-- 文本域 -->
                  <textarea
                    v-show="field.type === 'textarea'"
                    class="form-textarea"
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder"
                  />

                  <!-- 默认处理：未知类型显示为文本输入框 -->
                  <input
                    v-show="
                      ![
                        'text',
                        'number',
                        'selector',
                        'date',
                        'time',
                        'textarea',
                      ].includes(field.type)
                    "
                    class="form-input"
                    type="text"
                    v-model="formData[field.key]"
                    :placeholder="field.placeholder || '请输入'"
                  />
                </view>
              </template>
            </view>
          </template>
        </view>

        <view class="form-footer">
          <view class="form-btn cancel-btn" @click="handleCancel">{{
            cancelText
          }}</view>
          <view class="form-btn submit-btn" @click="handleSubmit">{{
            submitText
          }}</view>
        </view>
      </view>
    </view>
  </XenPageLayout>
</template>

<script setup lang="ts">
import { reactive, computed, onMounted, type PropType } from "vue";
import XenPageLayout from "@/layouts/XenPageLayout.vue";

// 定义字段配置接口
interface FormField {
  key: string;
  label: string;
  type: string; // text, number, selector, date, time, textarea
  placeholder?: string;
  required?: boolean;
  options?: string[];
  maxlength?: number;
  validator?: (value: any) => boolean | string;
}

// 定义表单分组接口
interface FormSection {
  title: string;
  fields: FormField[];
}

// 定义主题配置
interface ThemeConfig {
  primaryColor: string;
  secondaryColor: string;
  gradientStart?: string;
  gradientEnd?: string;
}

// 组件属性定义
const props = defineProps({
  // 页面标题
  pageTitle: {
    type: String,
    default: "表单",
  },
  // 表单标题
  headerTitle: {
    type: String,
    default: "填写信息",
  },
  // 表单副标题
  headerSubtitle: {
    type: String,
    default: "请填写完整信息",
  },
  // 表单分组与字段
  formSections: {
    type: Array as PropType<FormSection[]>,
    required: true,
  },
  // 初始表单数据
  initialData: {
    type: Object,
    default: () => ({}),
  },
  // 是否编辑模式
  isEdit: {
    type: Boolean,
    default: false,
  },
  // 取消按钮文本
  cancelText: {
    type: String,
    default: "取消",
  },
  // 提交按钮文本
  submitText: {
    type: String,
    default: "提交",
  },
  // 主题配置
  themeConfig: {
    type: Object as PropType<ThemeConfig>,
    default: () => ({
      primaryColor: "#7881de",
      secondaryColor: "#764ba2",
      gradientStart: "#667eea",
      gradientEnd: "#764ba2",
    }),
  },
});

// 事件
const emits = defineEmits(["cancel", "submit", "validate"]);

// 表单数据
const formData = reactive({ ...props.initialData });

// 计算样式
const gradientStyle = computed(() => {
  return `background: linear-gradient(135deg, ${
    props.themeConfig.gradientStart || props.themeConfig.primaryColor
  } 0%, ${
    props.themeConfig.gradientEnd || props.themeConfig.secondaryColor
  } 100%); padding: 0; height: 100vh; display: flex; flex-direction: column;`;
});

// 选择器变更
const handleSelectorChange = (key: string, e: any, options: string[]) => {
  const index = e.detail.value;
  formData[key] = options[index];
};

// 字段变更
const handleFieldChange = (key: string, value: any) => {
  formData[key] = value;
};

// 取消按钮
const handleCancel = () => {
  emits("cancel");
  uni.navigateBack();
};

// 验证表单
const validateForm = () => {
  // 获取所有字段
  const allFields: FormField[] = [];
  props.formSections.forEach((section) => {
    section.fields.forEach((field) => {
      allFields.push(field);
    });
  });

  // 验证必填字段
  for (const field of allFields) {
    if (
      field.required &&
      (!formData[field.key] || formData[field.key].trim() === "")
    ) {
      uni.showToast({
        title: `请${field.type === "selector" ? "选择" : "输入"}${field.label}`,
        icon: "none",
      });
      return false;
    }

    // 自定义验证器
    if (field.validator && formData[field.key]) {
      const validationResult = field.validator(formData[field.key]);
      if (validationResult !== true) {
        uni.showToast({
          title:
            typeof validationResult === "string"
              ? validationResult
              : `${field.label}格式不正确`,
          icon: "none",
        });
        return false;
      }
    }
  }

  return true;
};

// 提交表单
const handleSubmit = () => {
  // 表单验证
  if (!validateForm()) {
    return;
  }

  // 触发提交事件
  emits("submit", formData);

  // 模拟提交成功
  uni.showLoading({ title: props.isEdit ? "保存中..." : "提交中..." });
  setTimeout(() => {
    uni.hideLoading();
    uni.showToast({
      title: props.isEdit ? "保存成功" : "提交成功",
      icon: "success",
      success: () => {
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      },
    });
  }, 1500);
};

// 页面加载
onMounted(() => {
  // 如果是编辑模式，可以在这里处理特殊的数据格式化
  if (props.isEdit) {
    // 实际应用时，可能需要对日期时间等特殊字段进行处理
  }
});
</script>

<style lang="scss" scoped>
.form-container {
  flex: 1;
  padding: 16px;
  overflow-y: auto;

  .form-card {
    background: #ffffff;
    border-radius: 16px;
    box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
    overflow: hidden;

    .form-header {
      padding: 20px 24px;
      border-bottom: 1px solid #f0f0f0;

      .form-title {
        font-size: 18px;
        font-weight: 600;
        color: #333;
        display: block;
        margin-bottom: 4px;
      }

      .form-subtitle {
        font-size: 14px;
        color: #666;
      }
    }

    .form-content {
      padding: 24px;

      .form-section {
        margin-bottom: 24px;

        &:last-child {
          margin-bottom: 0;
        }

        .section-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
          margin-bottom: 16px;
          position: relative;
          padding-left: 12px;

          &::before {
            content: "";
            position: absolute;
            left: 0;
            top: 50%;
            transform: translateY(-50%);
            width: 4px;
            height: 16px;
            background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
            border-radius: 2px;
          }
        }
      }

      .form-item {
        margin-bottom: 16px;

        &:last-child {
          margin-bottom: 0;
        }

        .form-label {
          display: block;
          font-size: 14px;
          color: #333;
          margin-bottom: 8px;

          .required {
            color: #ff5252;
            margin-right: 4px;
          }
        }

        .form-input,
        .form-textarea,
        .form-picker {
          width: 100%;
          height: 42px;
          border: 1px solid #e0e0e0;
          border-radius: 8px;
          padding: 0 12px;
          font-size: 14px;
          color: #333;
          background: #f9f9f9;
          box-sizing: border-box;
          line-height: 42px;
          transition:
            border-color 0.3s ease,
            background-color 0.3s ease;

          &:focus {
            border-color: #7881de;
            background: #ffffff;
          }

          &::placeholder {
            color: #999;
          }

          &.has-error {
            border-color: #ff5252;
            background: #fff8f8;
          }
        }

        .form-textarea {
          height: 100px;
          padding: 12px;
          line-height: 1.5;
        }

        .form-picker {
          .picker-content {
            display: flex;
            align-items: center;
            justify-content: space-between;
            height: 100%;

            .picker-text {
              font-size: 14px;
              color: #333;

              &:empty::before {
                content: "请选择";
                color: #999;
              }
            }
          }
        }
      }
    }

    .form-footer {
      display: flex;
      padding: 16px 24px;
      border-top: 1px solid #f0f0f0;
      gap: 16px;

      .form-btn {
        flex: 1;
        height: 44px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 15px;
        font-weight: 500;
        transition: all 0.2s;

        &:active {
          opacity: 0.8;
        }

        &.cancel-btn {
          background: #f0f0f0;
          color: #666;
        }

        &.submit-btn {
          background: linear-gradient(135deg, #7579f5 0%, #9973f8 100%);
          color: #fff;
          box-shadow: 0 2px 8px rgba(107, 114, 242, 0.3);
        }
      }
    }
  }
}
</style>
